package org.database.quartz;

import java.lang.reflect.InvocationTargetException;

import org.dynamic.config.Application;
import org.quartz.InterruptableJob;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.quartz.UnableToInterruptJobException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 任务调度适配器
 *
 * @author huyj
 * @Created 2017-03-23 14:39
 */
public class TaskAdapter implements StatefulJob, InterruptableJob {
    private Logger logger = LoggerFactory.getLogger(getClass());
    public TaskAdapter() {}

    private TaskExecute taskExecute = null;

    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        /*Object taskExecuteObj = jobDataMap.get("targetObject");
       String targetMethod = jobDataMap.getString("targetMethod");*/
        TaskScheduled taskScheduled = (TaskScheduled) jobDataMap.get(Application.QUARTZ_DATA);
        Object taskExecuteObj = taskScheduled.getTargetObject();
        String targetMethod =taskScheduled.getTaskMethod();

        if(logger.isInfoEnabled()){
            logger.info("任务开始执行：{}.{}",taskScheduled.getTaskTarget(),targetMethod);
        }

        //指定已实现类
      /*  if (taskExecuteObj instanceof TaskExecute) {
            taskExecute = (TaskExecute) taskExecuteObj;
            taskExecute.execute(jobDataMap);
        } else {
            System.out.println("未知的任务执行类:" + taskExecuteObj.getClass());
        }*/


       /* ApplicationContext applicationContext = null;
        try {
            applicationContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
        } catch (SchedulerException e) {
            logger.error("获得ApplicationContext实例异常",e);
            e.printStackTrace();
        }*/
        try {
            //taskExecuteObj.getClass().getDeclaredMethod(targetMethod).invoke(taskExecuteObj,jobDataMap);
            taskExecuteObj.getClass().getDeclaredMethod(targetMethod,Object.class).invoke(taskExecuteObj,jobDataMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            logger.error("IllegalAccessException",e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            logger.error("InvocationTargetException",e);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            logger.error("NoSuchMethodException",e);
        }
    }

    @Override
    public void interrupt() throws UnableToInterruptJobException {
        taskExecute.interrupt();
    }
}
